﻿<template>
  <aside class="root">
    <header class="header">
      <div class="logo">
        <IconTextLogo />
      </div>
      <button @click="$emit('toggle')" class="toggle-btn" aria-label="Toggle Sidebar">
        <IconFoldSidebar />
      </button>
    </header>

    <div class="new-chat">
      <button class="new-chat-btn">
        <IconNewChat />
        <span>开启新对话</span>
      </button>
    </div>

    <nav class="history">
      <div v-for="(group, groupIndex) in historyData" :key="group.title" class="history-group">
        <h2 class="history-title">{{ group.title }}</h2>
        <ul class="history-list">
          <li 
            v-for="(item, itemIndex) in group.items" 
            :key="item.id" 
            class="history-item" 
            :class="{ 'history-item-selected': item.id === selectedId }"
            tabindex="0"
            @click="handleItemClick(groupIndex, itemIndex)"
          >
            <span class="history-item-text">{{ item.text }}</span>
            <button @click.stop="handleItemMenu" class="history-item-options" tabindex="0" aria-label="More options">
              <IconMoreOptions />
            </button>
          </li>
        </ul>
      </div>
    </nav>

    <footer class="footer">
      <button class="download">
        <IconDownload />
        <span>下载 App</span>
        <IconNewBadge class="download-badge" />
      </button>
      <button class="profile" @click.stop="handleAvatarClick">
        <div class="profile-avatar">
          <UserIcon />
        </div>
        <span class="profile-text">个人信息</span>
      </button>
    </footer>
  </aside>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import IconTextLogo from '../icons/IconTextLogo.vue';
import IconFoldSidebar from '../icons/IconClose.vue';
import IconNewChat from '../icons/IconNewChat.vue';
import IconMoreOptions from '../icons/IconMoreOptions.vue';
import IconDownload from '../icons/IconDownload.vue';
import IconNewBadge from '../icons/IconNewBadge.vue';
import UserIcon from '../icons/IconUser.vue';
import IconRename from "../icons/IconRename.vue";
import IconDelete from "../icons/IconDelete.vue";
import IconLogout from '../icons/IconLogout.vue';
import usePopMenu from '../pop-menu/usePopMenu';
import { useUserStore } from '@/store/user';
import { useRouter } from 'vue-router';

defineEmits(['toggle']);

// 假数据
const historyData = ref([
  {
    title: '7 天内',
    items: [
      { id: 1, text: 'Python图像识别模块封装命名建议' },
      { id: 2, text: 'Vue3组件开发最佳实践' },
      { id: 3, text: 'TypeScript类型系统深入理解' }
    ]
  },
  {
    title: '更早',
    items: [
      { id: 4, text: 'React Hooks使用技巧' },
      { id: 5, text: 'Node.js性能优化方案' },
      { id: 6, text: 'Node.js性能优化方案' },
      { id: 7, text: 'Node.js性能优化方案' },
      { id: 8, text: 'Node.js性能优化方案' },
      { id: 9, text: 'Node.js性能优化方案' },
      { id: 10, text: 'Node.js性能优化方案' },
      { id: 11, text: 'Node.js性能优化方案' },
      { id: 12, text: 'Node.js性能优化方案' },
      { id: 13, text: 'Node.js性能优化方案' },
      { id: 14, text: 'Node.js性能优化方案' },
      { id: 15, text: 'Node.js性能优化方案' },
      { id: 16, text: 'Node.js性能优化方案' },
      { id: 17, text: 'Node.js性能优化方案' },
      { id: 18, text: 'Node.js性能优化方案' },
      { id: 19, text: 'Node.js性能优化方案' },
      
    ]
  }
]);
const MENU_ITEMS = [
  {
    id: 'rename-item',
    icon: IconRename, // <-- 传递导入的组件
    title: '重命名',
    onClick: () => { console.log('Rename clicked!'); }
  },
  {
    id: 'delete-item',
    icon: IconDelete, // <-- 传递导入的组件
    title: '删除',
    color: 'rgb(239, 68, 68)', // 红色
    onClick: () => {
      if (confirm('Are you sure you want to delete?')) {
        console.log('Delete confirmed!');
      }
    }
  },
  {
    id: 'settings-item',
    // icon: SettingsIcon, // <-- 如果有 SettingsIcon，像上面一样传递
    // 如果没有图标，则省略 icon 属性或设为 undefined/null
    title: '设置 (No Icon)',
    onClick: () => { console.log('Settings clicked!'); }
  }
];

const selectedId = ref<number | null>(null);
const { toggle, show } = usePopMenu();
const userStore = useUserStore();
const router = useRouter();

// 获取用户显示信息（手机号或邮箱）
const userDisplayInfo = computed(() => {
  return userStore.phone_number || userStore.email || '未登录';
});

const handleItemClick = (groupIndex: number, itemIndex: number) => {
  const item = historyData.value[groupIndex].items[itemIndex];
  selectedId.value = item.id;
};

function handleItemMenu(e: PointerEvent) {
  console.log(e.clientX, e.clientY)
  toggle(MENU_ITEMS, e.clientX, e.clientY);
}

// 处理头像点击事件
function handleAvatarClick(e: PointerEvent) {
  console.log('open avatar menu item');
  const AVATAR_MENU_ITEMS = [
    {
      id: 'user-info',
      title: userDisplayInfo.value,
      color: '#000000', // 黑色字体
      onClick: () => { console.log('User info clicked!'); }
    },
    {
      id: 'logout',
      icon: IconLogout,
      title: '退出登录',
      color: 'rgb(239, 68, 68)', // 红色字体
      onClick: () => {
        if (confirm('确定要退出登录吗？')) {
          /// @ts-expect-error
          userStore.logout();
          router.push('/login');
          console.log('User logged out!');
        }
      }
    }
  ];
  // toggle(AVATAR_MENU_ITEMS, e.clientX, e.clientY);
  show(AVATAR_MENU_ITEMS, e.clientX, e.clientY);
}
</script>

<style lang="scss" scoped>
@use "sass:color";

$sidebar-bg: #f9fbff; // rgb(249, 251, 255)
$text-primary: #262626; // rgb(38, 38, 38)
$text-secondary: #525252; // rgb(82, 82, 82)
$text-tertiary: #555555; // rgb(85, 85, 85)
$text-muted: #8b8b8b; // rgb(139, 139, 139)
$icon-color: rgb(139, 139, 139);
$logo-color: #2c2c36; // rgb(44, 44, 54)
$profile-icon-bg: #babac1; // rgb(186, 186, 193) - Assuming this is the intended color for the placeholder
$new-chat-bg: #dbeafe; // rgb(219, 234, 254)
$new-chat-text: #4d6bfe; // rgb(77, 107, 254)
$download-border: #4d6bfe;
$sidebar-width: 260px;

.root {
  background-color: $sidebar-bg;
  display: flex;
  flex-direction: column;
  width: $sidebar-width;
  max-width: $sidebar-width;
  height: 100%;
  color: $text-secondary;
  font-size: 14px;
  line-height: 1.4;
  font-family: 'DeepSeek-CJK-patch', Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", Ubuntu, Cantarell, "Helvetica Neue", Oxygen, "Open Sans", sanserif;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 25px 10px 34px 20px;
    height: 90px; // Keep fixed height if required by design
    box-sizing: border-box;
    flex-shrink: 0;
  }

  .logo {
    display: flex; // To contain the SVG
    align-items: center;
    color: $logo-color; // SVG uses currentColor
    svg {
      height: 26px;
      width: auto; // Maintain aspect ratio
    }
  }

  .toggle-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    color: $icon-color;
    border-radius: 8px; // Add some rounding for focus state
    padding: 3px;
    box-sizing: content-box;
    svg {
      width: 28px; // Use width/height on SVG directly if fixed size needed
      height: 28px;
    }
    &:hover {
      background-color: rgba(0, 0, 0, 0.05);
    }
  }

  .new-chat {
    display: flex; // Center the button if needed
    align-items: center;
    margin-bottom: 34px; // As per original DIV-6
    padding: 0 14px; // Approximated from original margin
  }

  .new-chat-btn {
    display: flex;
    align-items: center;
    background-color: $new-chat-bg;
    color: $new-chat-text;
    border-radius: 14px;
    font-size: 16px;
    font-weight: 500;
    height: 44px;
    line-height: 20px;
    padding: 0 15px; // Adjusted padding
    width: auto; // Fit content
    transition: background-color 0.2s ease;

    svg {
      width: 22px;
      height: 22px;
      margin-right: 9px;
    }
    &:hover {
      background-color: #c6dcf8;
    }
  }

  .history {
    flex: 1 1 0; // Take remaining space
    overflow-y: auto; // Enable scrolling for history
    padding: 0 10px; // Padding for the history section
    position: relative; // Needed for sticky title and gradient overlay
  }

  .history-group {
    position: relative; // For potential sticky elements within
    // Add margin/padding between groups if needed
  }

  .history-title {
    background-color: $sidebar-bg; // Match sidebar bg
    color: $text-tertiary;
    font-size: 13px;
    font-weight: 600;
    line-height: 18px;
    margin: 0 0 6px 0; // Adjusted margin
    padding: 6px 10px 6px 6px; // Adjusted padding to align roughly with items
    position: sticky; // Make title sticky
    top: 0;
    z-index: 2;
  }

  .history-list {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  .history-item {
    display: flex;
    align-items: center;
    background-color: $sidebar-bg; // Default background
    border-radius: 12px;
    color: $text-primary;
    cursor: pointer;
    font-size: 14px;
    height: 38px;
    padding: 0 10px;
    position: relative; // For positioning options button and gradient
    margin-bottom: 4px; // Add space between items
    overflow: hidden; // Needed for text overflow and gradient
    transition: background-color 0.2s ease;

    &:hover {
      background-color: #eff6ff;
      .history-item-options {
        opacity: 1;
      }
      // Modify gradient on hover if desired
      &::after {
        opacity: 0; // Hide gradient on hover/focus to show full text
      }
    }

    &.history-item-selected {
      background-color: #dbeafe;
      &::after {
        opacity: 0;
      }
    }

    // Gradient overlay for text truncation indication
    &::after {
      content: "";
      position: absolute;
      top: 0;
      bottom: 0;
      right: 0;
      width: 50px; // Adjust width as needed
      background: linear-gradient(to left, $sidebar-bg 30%, rgba($sidebar-bg, 0) 100%);
      pointer-events: none; // Allow clicks through
      transition: opacity 0.2s ease;
      // Original had two gradients, simplifying to one common effect
    }
  }

  .history-item-text {
    flex: 1 1 0; // Take available space
    line-height: 18px;
    min-width: 0; // Prevent flex item from growing too large
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding-right: 30px; // Space for the options button
  }

  .history-item-options {
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    width: 24px;
    height: 24px;
    opacity: 0; // Hidden by default, show on hover/focuwithin parent
    position: absolute;
    right: 10px;
    top: 50%; // Center vertically
    transform: translateY(-50%);
    z-index: 1;
    color: $text-primary; // Icon color
    transition: opacity 0.2s ease, background-color 0.2s ease;

    &:hover {
      background-color: rgba(0, 0, 0, 0.1);
    }

    svg {
      width: 16px;
      height: 16px;
    }
  }


  .footer {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px 12px;
    flex-shrink: 0; // Prevent footer from shrinking
    border-top: 1px solid color.adjust($sidebar-bg, $lightness: -5%); // Add a subtle separator
  }

  .download {
    display: flex;
    align-items: center;
    border: 0.8px solid $download-border;
    border-radius: 12px;
    color: $text-primary;
    font-size: 14px;
    font-weight: 400; // Was default, explicit here
    padding: 9px 12px;
    width: 100%; // Use full width of padding area
    box-sizing: border-box;
    margin-bottom: 8px;
    text-align: left;
    transition: background-color 0.2s ease;

    &:hover {
      background-color: rgba($download-border, 0.05);
    }

    svg:first-of-type { // Target IconDownload
      width: 20px;
      height: 20px;
      margin-right: 8px;
    }

    span {
      flex-grow: 1; // Push badge to the right
    }
  }

  .download-badge {
    // The SVG itself has fixed dimensions (36x16)
    display: flex; // Ensure it aligns if needed
    margin-left: 8px;
    flex-shrink: 0; // Prevent badge from shrinking
  }

  .profile {
    display: flex;
    align-items: center;
    border-radius: 12px;
    padding: 8px;
    width: 100%; // Use full width of padding area
    box-sizing: border-box;
    text-align: left;
    transition: background-color 0.2s ease;

    &:hover {
      background-color: rgba(0, 0, 0, 0.03);
    }
  }

  .profile-avatar {
    display: flex; // Center icon if needed
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    width: 32px;
    height: 32px;
    overflow: hidden;
    flex-shrink: 0;
    // background-color: $profile-icon-bg; // Optional: Set background if icon doesn't fill
    color: $profile-icon-bg; // Color for the UserIcon SVG

    svg {
      width: 32px;
      height: 32px;
    }
  }

  .profile-text {
    color: $text-secondary;
    font-size: 14px;
    margin-left: 8px;
    user-select: none; // Keep user-select if needed
  }
}
</style>